package org.example.commonapi.util.redis;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 获取对象封装方法
     * @param prefix
     * @param key
     * @return 报错返回null
     * @param <T>
     */
    public <T> T get(Prefix prefix,String key){
        //prefix为键前缀
        //key为正式键
        //生成真正的key,连接键前缀和键
        String realKey = prefix.getPrefix() + key;
        return (T)redisTemplate.opsForValue().get(realKey);
    }

    /**
     * 设置对象封装方法
     * @param key
     * @param value
     */
    public <T> Boolean set(Prefix prefix,String key,T value,int exTime){
        //prefix为键前缀
        //key为正式键
        //value为值
        //exTime为过期时间
        //生成真正的key,连接键前缀和键
        String realKey = prefix.getPrefix() + key;
        try {
            //如果过期时间>0
            if (exTime > 0) {
                redisTemplate.opsForValue().set(realKey, value, exTime, TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().set(realKey, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public Boolean del(Prefix prefix,String key) {
        String realKey = prefix.getPrefix() + key;
        return redisTemplate.delete(realKey);
    }

}
